#!/bin/bash
set -u

RESOURCES="$(cd "$(dirname "$0")/../Resources" && pwd)"

alert() {
  /usr/bin/osascript -e 'on run argv' -e 'display alert (item 1 of argv) message (item 2 of argv) as critical' -e 'end run' "$1" "$2"
}

roots=(
  "$HOME/Library/Application Support/PrismLauncher/instances"
  "$HOME/Library/Application Support/PolyMC/instances"
)
matches=()
for root in "${roots[@]}"; do
  [[ -d "$root" ]] || continue
  while IFS= read -r -d '' cfg; do
    instance="$(dirname "$cfg")"
    if [[ -f "$instance/mmc-pack.json" ]] && /usr/bin/grep -q 'All the Mods 10' "$instance/instance.cfg"; then
      matches+=("$instance")
    fi
  done < <(/usr/bin/find "$root" -mindepth 2 -maxdepth 2 -name instance.cfg -print0)
done

if [[ ${#matches[@]} -eq 0 ]]; then
  alert "ATM10 was not found" "Install ATM10 8.1 in Prism Launcher, launch it once, close the game, and open this setup app again."
  exit 2
fi

if [[ ${#matches[@]} -eq 1 ]]; then
  instance="${matches[0]}"
else
  instance=$(/usr/bin/osascript - "${matches[@]}" <<'OSA'
on run argv
  set picked to choose from list argv with title "BoalHaus ATM10 Setup" with prompt "Choose the ATM10 8.1 instance to configure:" OK button name "Continue" cancel button name "Cancel"
  if picked is false then return ""
  return item 1 of picked
end run
OSA
  )
  [[ -n "$instance" ]] || exit 0
fi

if ! /usr/bin/osascript - "$instance" <<'OSA'
on run argv
  display dialog "BoalHaus will verify ATM10 8.1, back up replaced files, and install two compatibility mods into:" & return & return & item 1 of argv with title "BoalHaus ATM10 Setup" buttons {"Cancel", "Install"} default button "Install" cancel button "Cancel"
end run
OSA
then
  exit 0
fi

log="$(/usr/bin/mktemp -t boalhaus-atm10-setup)"
work="$(/usr/bin/mktemp -d -t boalhaus-atm10-work)"
cleanup() { /bin/rm -rf "$work"; }
trap cleanup EXIT

install_profile() {
  cfg="$instance/instance.cfg"
  pack="$instance/mmc-pack.json"
  /usr/bin/grep -q '^ManagedPackName=All the Mods 10' "$cfg" || { echo "This is not an All the Mods 10 instance."; return 1; }
  /usr/bin/grep -q '^ManagedPackVersionName=8.1' "$cfg" || { echo "ATM10 version 8.1 is required."; return 1; }
  /usr/bin/grep -q '"uid"[[:space:]]*:[[:space:]]*"net.minecraft"' "$pack" || { echo "Minecraft metadata is missing."; return 1; }
  /usr/bin/grep -q '"version"[[:space:]]*:[[:space:]]*"1.21.1"' "$pack" || { echo "Minecraft 1.21.1 is required."; return 1; }
  /usr/bin/grep -q '"uid"[[:space:]]*:[[:space:]]*"net.neoforged"' "$pack" || { echo "NeoForge is required."; return 1; }

  game="$instance/minecraft"
  [[ -d "$game" ]] || game="$instance/.minecraft"
  [[ -d "$game" ]] || { echo "Launch ATM10 once before running setup."; return 1; }
  mods="$game/mods"
  /bin/mkdir -p "$mods"

  compat_source="$RESOURCES/artifacts/boalhaus-client-compat-0.5.4.jar"
  negotiator="$work/be_quiet_negotiator-1.0.4.jar"
  /usr/bin/curl -fL --retry 2 -o "$negotiator" 'https://cdn.modrinth.com/data/38x4KgoC/versions/OkXxbMBg/be_quiet_negotiator-1.0.4.jar'

  compat_hash="$(/usr/bin/shasum -a 512 "$compat_source" | /usr/bin/awk '{print $1}')"
  negotiator_hash="$(/usr/bin/shasum -a 512 "$negotiator" | /usr/bin/awk '{print $1}')"
  [[ "$compat_hash" == '63c51493b6ee19b0de07e91a7d9e3bdd199b1bf6e501e43ecef346ccd6d878aab6af739531e70e73891dc662d64b6d89e26f59e68db6dc9d420bcf04feae1375' ]] || { echo "BoalHaus compatibility hash verification failed."; return 1; }
  [[ "$negotiator_hash" == '376ef0d83753398b286bd841791a2270d75e81022574dbe3849bcd56c86937835400e600a2b39c5553193edeb6973a85f06320fea8557e0da3e7232995cf24f9' ]] || { echo "Be Quiet Negotiator hash verification failed."; return 1; }

  stamp="$(/bin/date -u +%Y%m%dT%H%M%SZ)"
  backup="$game/.boaltech/backups/$stamp/mods"
  /bin/mkdir -p "$backup"
  shopt -s nullglob
  old_files=("$mods"/boalhaus-client-compat-*.jar "$mods"/be_quiet_negotiator-*.jar "$mods"/be-quiet-negotiator-*.jar)
  for old in "${old_files[@]}"; do
    /bin/mv "$old" "$backup/"
  done
  /bin/cp "$compat_source" "$mods/boalhaus-client-compat-0.5.4.jar"
  /bin/cp "$negotiator" "$mods/be_quiet_negotiator-1.0.4.jar"

  [[ "$(/usr/bin/shasum -a 512 "$mods/boalhaus-client-compat-0.5.4.jar" | /usr/bin/awk '{print $1}')" == "$compat_hash" ]]
  [[ "$(/usr/bin/shasum -a 512 "$mods/be_quiet_negotiator-1.0.4.jar" | /usr/bin/awk '{print $1}')" == "$negotiator_hash" ]]
  echo "Installed and verified both compatibility mods."
  echo "Backup: $backup"
}

if install_profile >"$log" 2>&1; then
  /usr/bin/osascript -e 'display dialog "Compatibility was installed and verified. Start ATM10 8.1 and connect to mc.boal.tech." with title "BoalHaus is ready" buttons {"Done"} default button "Done" with icon note'
  /bin/rm -f "$log"
  exit 0
fi

details="$(/usr/bin/tail -c 3500 "$log")"
/usr/bin/osascript - "$details" <<'OSA'
on run argv
  display alert "Setup could not be completed" message (item 1 of argv) as critical
end run
OSA
/bin/rm -f "$log"
exit 1
